import { ITodoData } from "./typing"

class TodoEvent {
    private todoData: ITodoData[] = []
    private static instance: TodoEvent

    constructor() {

    }

    public static create() {
        if (!TodoEvent.instance) {
            return TodoEvent.instance = new TodoEvent()
        }
        return TodoEvent.instance
    }

    public addTodo(todo: ITodoData): Promise<ITodoData> {
        return new Promise((resolve, reject) => {
            const todoIndex = this.todoData.findIndex((todoItem: ITodoData) => todoItem.content === todo.content)
            if (todoIndex === -1) {
                alert('内容重复')
                reject('1001')
            }
            this.todoData.push(todo)
            resolve(todo)
        })
    }

    public removeTodo(id: number): Promise<void> {
        return new Promise((resolve, reject) => {
            this.todoData = this.todoData.filter((todoItem: ITodoData) => todoItem.id !== id)
            resolve()
        })
    }

    public toggleComplete(id: number): Promise<void> {
        return new Promise((resolve, reject) => {
            this.todoData = this.todoData.map((todoItem: ITodoData) => {
                if (todoItem.id === id) {
                    todoItem.completed = !todoItem.completed
                }
                return todoItem
            })
            resolve()
        })
    }
}

export default TodoEvent